#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>

#include "modelManager.h"
#include "stringFunctions.h"


bool modelManager::loadModel(std::string path)
{
    std::string fileName = getFileName(path);
    std::string fileExt = getFileExt(fileName);
    if(fileExt.compare(".obj") != 0)
        return false;

	objModel* m = new objModel();
	m->load((char*)path.c_str());
	m->id = fileName;

	model.push_back(m);
	std::cout << "Model loaded " << path << "\n";
	return true;
}

bool modelManager::displayModel(std::string id, float xPos, float yPos, float zPos, float xRot, float yRot, float zRot, std::string matName)
{
	std::vector<objModel*>::iterator it;
	for(it = model.begin(); it != model.end(); it++)
	{
		if((*it)->id == id)
		{
			(*it)->display(xPos, yPos, zPos, xRot, yRot, zRot, matName);
			return true;
		}
	}
	std::cout << "Error, could not find " << id << " was it loaded correctly?\n";
	return false;
}

std::string modelManager::getMatName(std::string id, int matGroup)
{
	for(int x=0; x<model.size(); x++)
	{
		if(model[x]->id.compare(id) == 0)
		{
			return model[x]->getMatName(matGroup);
		}

	}
}

int modelManager::getNumMatGroups(std::string id)
{

	for(int x=0; x<model.size(); x++)
	{
		if(model[x]->id.compare(id) == 0)
		{
			return model[x]->numMatGroups();
		}

	}

}



modelManager* MM()
{
	return modelManager::instance();
}
modelManager::modelManager()
{
//... perform necessary instance initializations
}
modelManager* modelManager::pinstance = 0;// initialize pointer

modelManager* modelManager::instance()
{
	if (!pinstance)
	{
		pinstance = new modelManager; // create sole instance
	}
	return pinstance; // address of sole instance
}

modelManager::~modelManager()
{
	std::vector<objModel*>::iterator it;
	for(it = model.begin(); it != model.end(); it++)
	{
		delete (*it);
	}
}

using namespace boost::filesystem; //ALSO CHANGE TO READ LINE INSTEAD OF READ CHARACTER!!!
using namespace std;
void loadModelDirectory(const boost::filesystem::path & directory, bool recurse_into_subdirs)
{
    directory_iterator end;

    for( directory_iterator iter(directory) ; iter != end ; ++iter )
    {
        if ( is_directory( *iter ) )
        {
            if( recurse_into_subdirs ) loadModelDirectory(*iter, true) ;
        }
        std::stringstream s;
        s << iter->path();
        std::string out; s >> out;

        MM()->loadModel(out);
    }
}